var async = require('async');
var AV = require('leanengine');

require('../app.js');
//购物车相关模型信息
var ActivityM = AV.Object.extend('Activity');
var queryAct = new AV.Query(ActivityM);
//个人限购
var personalLimitBuyM = AV.Object.extend('LimitBuyRecord');

module.exports = {
    /**
     * 获取活动规则limitCondition
     * 流程：判断psid是否包含，如果包含读取date，判断startDate是否满足，如果满足，读取loop，根据loop的情况判断读取time，将符合条件的limitCondition返回
     *      判断pid是否包含，...
     *      判断cid是否包含, ...
     *      将不满足条件 的情况返回：｛code:1,canAccount:0,limitCondition:limitCondition｝
     *      满足情况的返回值：｛code:0,canAccount:1,limitCondition:limitCondition｝
     * @param psid
     * @param pid
     * @param cid
     * @returns {*}
     */
    getLimitCondition:function(psid,pid,cid,uid){
        if(!psid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        if(!pid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        if(!cid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        psid = psid+'';
        pid = pid+'';
        cid= parseInt(cid);
        uid = uid+'';
        var promise = new AV.Promise() ;
        //var activity = global.initData.activity ;
        var finalResult = new Array();
        var canAccount = 1 ;   //canAccount=1：允许立即支付，=0，不允许立即支付
        var isInDate = 0;
        var isInTime = 0;
        var isLoop = 0;
        var limitPersonalBought=0;
        var normalProduct = 1 ;
        var limitCondition = {} ;

        //根据objectid删除对应的内容
        async.auto({
            getActivityInfo:function(callback){
                var query = new AV.Query(ActivityM);
                query.equalTo('status','1');
                //活动结束时间大于当前时间
                //将普通时间转换为时间戳，进行比较
                query.greaterThanOrEqualTo('endDate',Math.round(new Date().getTime()/1000));
                query.find().then(function(res){
                    var actInfo = new Array();
                    async.eachSeries(res,function(act,callback1){
                        actInfo.push(act);//JSON.stringify
                        callback1(null, actInfo);
                    },function(){
                        callback(null,{activity:actInfo});
                    });
                }).catch(function(err){
                    callback(null, {activity:{}});
                });
            },
            getLimitInfo:['getActivityInfo',function(callback,results){

                var activity = results.getActivityInfo.activity;
                finalResult = [] ;
                if(!activity || activity.length<1 || activity==='undefined'){
                    return callback(null, {code:1,finalResult:{canAccount:canAccount,isInDate:isInDate,isInTime:isInTime,isLoop:isLoop,normalProduct:normalProduct,limitPersonalBought:limitPersonalBought,limitCondition:limitCondition,actInfo:{}}})
                }else{
                    async.eachSeries(activity,function(res,callback1){
                        if((res.get('specids').indexOf(psid)!=-1 || res.get('pids').indexOf(pid)!=-1 || res.get('cids').indexOf(cid)!=-1)){
                            //存在，再判断时间是否满足（date，主要是开始时间和当前时间的比较），如果满足，再判断loop，
                            //判断开始时间是否满足
                            normalProduct = 0 ;
                            if(Math.round(new Date().getTime()/1000) - res.get('startDate') >= 0 && Math.round(new Date().getTime()/1000) - res.get('endDate') <= 0){
                                //console.log(Math.round(new Date().getTime()/1000) +":"+res.get('endDate'));
                                isInDate = 1 ;
                                if(res.get('loop') === '1'){
                                    //判断是否循环，比较当前时间是否满足条件，
                                    isLoop = 1 ;
                                    var startTime = new Date(new Date().toLocaleDateString()+' '+new Date(res.get('startTime') * 1000).toLocaleTimeString());
                                    var endTime = new Date(new Date().toLocaleDateString()+' '+new Date(res.get('endTime') * 1000).toLocaleTimeString())
                                    if(new Date()-startTime >=0  && new Date()- endTime<=0){
                                        isInTime = 1 ;
                                        canAccount = 1;
                                    }else{
                                        isInTime = 0 ;
                                        canAccount = 0;
                                    }
                                }else{
                                    isLoop = 0 ;
                                }
                            }else{
                                isInDate = 0 ;
                            }
                            limitCondition = res.get('limitCondition');
                            finalResult.push({canAccount:canAccount,isInDate:isInDate,isInTime:isInTime,isLoop:isLoop,normalProduct:normalProduct,limitPersonalBought:limitPersonalBought,limitCondition:limitCondition,actInfo:res});
                        }
                        callback1(null,finalResult);
                    },function(){
                        //console.log(finalResult);
                        callback(null, {finalResult:finalResult})
                    });
                }

            }],

            setLimitInfo:['getLimitInfo',function(callback,results){
                var finalResult = results.getLimitInfo.finalResult;
                if(!finalResult || finalResult.length<1 || finalResult==='undefined'){
                    canAccount = 1 ;   //canAccount=1：允许立即支付，=0，不允许立即支付
                    isInDate = 0;
                    isInTime = 0;
                    isLoop = 0;
                    normalProduct = 1 ;
                    limitPersonalBought=0;
                    limitCondition = {} ;
                    callback(null, {code:2,finalResult:{canAccount:canAccount,isInDate:isInDate,isInTime:isInTime,isLoop:isLoop,normalProduct:normalProduct,limitPersonalBought:limitPersonalBought,limitCondition:limitCondition,actInfo:{}}});
                    return ;
                }
                /*if(finalResult.length===1){
                    if(finalResult[0].normalProduct === 1){
                        canAccount = 1 ;   //canAccount=1：允许立即支付，=0，不允许立即支付
                        isInDate = 0;
                        isInTime = 0;
                        isLoop = 0;
                        normalProduct = 1 ;
                        limitCondition = {} ;
                        return callback(null, {code:3,finalResult:{canAccount:canAccount,isInDate:isInDate,isInTime:isInTime,isLoop:isLoop,normalProduct:normalProduct,limitPersonalBought:limitPersonalBought,limitCondition:limitCondition,actInfo:finalResult[0].actInfo}})
                    }
                }*/
                var realResult ={};
                async.eachSeries(finalResult,function(eachRes,callback1){
                    if(eachRes.normalProduct === 0){
                        if(JSON.stringify(realResult)==="{}"){
                            realResult = eachRes;
                        }
                        if(eachRes.actInfo.get('startDate') >= realResult.actInfo.get('startDate')){
                            realResult = eachRes ;
                        }
                    }
                    callback1(null, realResult);
                },function(){
                    if(JSON.stringify(realResult)=="{}"){
                        realResult={canAccount:1,isInDate:0,isInTime:0,isLoop:0,normalProduct:1,limitPersonalBought:0,limitCondition:{},actInfo:{}};
                    }
                    return  callback(null,  {code:4,finalResult:realResult});
                });
            }],
            getLimitPersonalBought:['setLimitInfo',function(callback,results){
                var finalResult = results.setLimitInfo.finalResult ;
                if(finalResult.normalProduct===0 && finalResult.limitCondition.ueach!=0){
                    var query = new AV.Query(personalLimitBuyM);
                    query.equalTo('uid',uid+'');
                    query.equalTo('pid',pid+'');
                    query.equalTo('sid',psid+'');
                    query.equalTo('cid',cid);
                    query.equalTo('aid',finalResult.actInfo.id);
                    query.count().then(function(count){
                        //已购买订单数
                        finalResult['limitPersonalBought'] = count;
                        return callback(null, results.setLimitInfo);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                }else{
                    callback(null,results.setLimitInfo) ;
                }
            }]
        },function(err,results){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(results.getLimitPersonalBought);
            }
        });
        return promise;
    },

};